// 引入Node.js的net模块用于网络通信
const net = require('net');

// 创建TCP服务器
const server = net.createServer((socket) => {
    let remote_addr =  socket.remoteAddress + socket.remotePort
    console.log('新用户连接: ',remote_addr);

    // 当接收到数据时触发
    socket.on('data', (data) => {
        let buffer = Array.from(data)

        console.log(`${getFormattedDateTime()}[recv] str= ${data.toString().trim()}, buffer= ${buffer}`);
        // 发送回应给客户端
        socket.write('OK'); // OK在ASCII码中等于 4F 4B ; 46 55 43 4B
    });

    // 当客户端断开连接时触发
    socket.on('end', () => {
        console.log('用户离线',remote_addr);
    });
});

// 监听特定端口和地址
server.listen(10086, '0.0.0.0', () => {
    console.log('Server is listening for connections on port 10086');
});

// 错误处理
server.on('error', (err) => {
    throw err;
});


/*--- 下面开始为工具函数 ---*/
function getFormattedDateTime() {
    const now = new Date();
    
    const year = now.getFullYear();
    const month = String(now.getMonth() + 1).padStart(2, '0'); // 月份从0开始，所以需要加1
    const day = String(now.getDate()).padStart(2, '0');
    
    const hour = String(now.getHours()).padStart(2, '0');
    const minute = String(now.getMinutes()).padStart(2, '0');
    const second = String(now.getSeconds()).padStart(2, '0');
    const millisecond = String(now.getMilliseconds()).padStart(3, '0');
    
    return `${year}-${month}-${day} ${hour}:${minute}:${second}.${millisecond}`;
}

